import {getToken, getUserId, removeToken, removeUserId, setToken, setUserId} from "../../utils/auth";
import {getInfo, login, logout} from "../../api/login";


const user = {
  state: {
    token: getToken(),
    userId: getUserId(),
    userInfo: {}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
    },
    SET_USER: (state, user) => {
      state.userInfo = user
    }
  },
  actions: {
    // 登录
    Login({commit}, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        login(username, password).then(res => {
          setToken(res.data.token)
          setUserId(res.data.id)
          commit('SET_TOKEN', res.data.token)
          commit('SET_USER_ID', res.data.id)
          commit('SET_USER', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        getInfo({id:state.userId}).then(res => {
          commit('SET_USER', res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出系统
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_USER_ID', null)
          commit('SET_USER', null)
          removeToken()
          removeUserId()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  },
}

export default user
